/**
 * 提交申请
 * data :{
 *  SQDH:SQDH,
            yyzzfjUrl: {
                isLocal: false,
                val: yyzzUrl,
                filePath: "",
            },
            sqwtsfjUrl: {
                isLocal: false,
                val: sqwtsUrl,
                filePath: "",
            },
            qymc: KSMC,
            shtyxydm: KSSH,
            zlshcq: SPCQH,
            // 审批进度与意见
            spjdyyj: SPYJ,
 * }
 */
function submitData(data, callback) {
    uploadYYZZ(data, callback);
}

function uploadYYZZ(params, callback) {
    const yyzzfjUrl = params.yyzzfjUrl;
    if (!yyzzfjUrl.isLocal) {
        const xhr = new XMLHttpRequest();
        xhr.open("get", yyzzfjUrl.val);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            console.log(arguments);
            uploadSQWT({ ...params, BusinessLicense: "" }, callback)
        }

    } else {
        uploadSQWT({ ...params, BusinessLicense: yyzzfjUrl.val }, callback)
    }
}

function uploadSQWT(params, callback) {
    const sqwtsfjUrl = params.sqwtsfjUrl;
    if (!sqwtsfjUrl.isLocal) {
        const xhr = new XMLHttpRequest();
        xhr.open("get", sqwtsfjUrl.val);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            console.log(arguments);
            callback({ ...params, DelegationOfAuthority: "" }, callback);
        }

    } else {
        callback({ ...params, DelegationOfAuthority: sqwtsfjUrl.val }, callback);
    }
}

/**
 * @param {*} param 
 * param = {
 *      action : "UserAuthCompanyCreate",
 *      CustomNo: string, // 留空
 *      CustomName: string, // 企业名称，
 *      CompanyTaxNum:string,// 企业税号
 *      FirstSubmit:'Y'|'N', // 是否首次提交 ysqdh
 *      OldOrderNo : string, // ysqdh
 *      FactoryNo : string, // 资料审核工厂
 *      FactoryName : string ,// 工厂名称
 *      BusinessLicense : string ,// 格式->D:\xxx\xx
 *      DelegationOfAuthority : string 格式->D:\xxx\xx
 * 
 * CustomNo : "",
            CustomName : qymc||"",
            CompanyTaxNum : shtyxydm||"",
            FirstSubmit : !ysqdh ? "Y":"N",
            OldOrderNo : ysqdh,
            FactoryNo : zlshcq[0],
            FactoryName : shcqzl.filter(item=>item.value == zlshcq[0])[0].label,
            BusinessLicense : yyzzfj.originFile,
            DelegationOfAuthority : sqwtsfj.originFile
 * }
 */
function submitWithParam(param) {
    $.ajax({
        url: REQUEST_URL,
        type: "post",
        data: JSON.stringify({ action: "UserAuthCompanyCreate", ...param }),
        contentType: "application/json",
        headers: REQUEST_HEADERS(),
        success: function (r, t, x) {
            layer.msg(r.message);
            if(r.code == 200){
                setTimeout(() => {
                    history.go(-1)
                }, 2000);
            }
            
        }
    })
}


/**加载以前提交的历史记录*/
function loadSubmitRecord() {
    console.log('start load')
    const companyNumber = getUrlParam("companyNumber");
    if (!companyNumber) {
        return;
    }
    const loadingIndex = layer.load();
    $.ajax({
        url: REQUEST_URL,
        type: "post",
        data: JSON.stringify({ action: "GetUserAuthCompanyDetail", CompanyNumber: companyNumber }),
        headers: REQUEST_HEADERS(),
        contentType: "application/json",
        success: function (r, t, x) {
            console.log('history', r)
            layer.close(loadingIndex)
            const res = responseHandler(r, t, x);
            if (res.code == 200) {
                initialData(res);
            }
        },
        error: function () {
            layer.close(loadingIndex)
        }
    })
}


function parseYYZZ(file) {
    const data = new FormData();
    data.append("file", file)
    $.ajax({
        url: "https://ssl.zhuanyegou.com/fileServer/ocr/business",
        type: "post",
        data: data,

        processData: false,
        contentType: false,
        success: function (r, t, x) {
            layer.close(yyzzLoadingIndex)
            console.log("上传成功" + r);
            try {
                const dataJson = r.data;
                const companyInfo = JSON.parse(dataJson);
                const {
                    RegistrationDate,
                    businessAddress,
                    businessScope,
                    companyForm,
                    companyName,
                    companyType,
                    creditCode,
                    legalPerson,
                    registeredCapital,
                    validFromDate,
                    validPeriod,
                    validToDate,
                } = companyInfo.data;
                $("#qymc").val(companyName);
                $("#shtyxydm").val(creditCode);


            } catch (err) {
                layer.msg("营业执照解析失败，请上传清晰且正确的营业执照");
            }
            data["yyzzfjUrl"] = {
                isLocal: true,
                val: window.URL.createObjectURL(file)
            }
            $("#yyzz-file").attr("src", data['yyzzfjUrl'].val)
            $("#yyzz-file").css({ "display": "" })

        },
        error: function (x, t, e) {
            layer.close(yyzzLoadingIndex)
            console.log("上传异常:" + e)
        }
    })
}


function clickShow(title, currentVal, opts, onSelectCallBack, document) {
    $("#opt").css({ "display": "none" })
    zlshcq_layer_index = layer.open({
        title: title || "请选择资料审核厂区",
        type: 1,
        content: $("#opt"),
    })


}

var zlshcq_layer_index = "";



function loadSHCQ() {
    $.ajax({
        url: REQUEST_URL,
        data: JSON.stringify({ action: "GetArchiveAuditFactory" }),
        type: "post",
        contentType: "application/json",
        headers: REQUEST_HEADERS(),
        success: function (r, t, x) {
            console.log(r)
            const res = responseHandler(r, t, x);
            if (res.code == 200) {
                renderOpt(data.zlshcq, res.list[0].Rows);
            }
        }
    })
}

function renderOpt(val, options) {
    // $("#opt").children().remove();
    options.forEach(item => {
        const ele = `
                            <div class="opt-item" id="shcq-item-${item.GSH}">
        <div>
            <img id="shcq-item-${item.GSH}-img" src=${item.GSH == val ? "./static/opt-checkbox.png" : "./static/opt-checkbox-unselect.png"} style="width: 20px;height:20px"/>
        </div>
        <div id="shcq-item-${item.GSH}-title">${item.GSMC}</div>
    </div>
                            `
        $("#opt").append(ele);
        $(`#shcq-item-${item.GSH}`).click(function () {
            console.log('click ', item, options, data)
            $("#opt").css({ "display": "none" })
            $(`#shcq-item-${data.zlshcq}-img`).attr("src", "./static/opt-checkbox-unselect.png");
            console.log($(`#shcq-item-${item.GSH}-img`))
            $(`#shcq-item-${item.GSH}-img`).attr("src", "./static/opt-checkbox.png");
            // $(`#shcq-item-${item.GSH}-img`).css({"display":"none"})
            data['zlshcq'] = item.GSH;
            $(`#shcq`).val(item.GSMC);

            layer.close(zlshcq_layer_index)

            // renderOpt(data['zlshcq'],options)

        })
    })
}

function loseFocus() {
    $("#shyj").blur();
}

function submit() {

    submitData(data, submitWithParam)
}


var data = {
    SQDH: undefined,
    yyzzfjUrl: {
        isLocal: true,
        val: "",
        filePath: "",
    },
    sqwtsfjUrl: {
        isLocal: true,
        val: "",
        filePath: "",
    },
    qymc: "",
    shtyxydm: "",
    zlshcq: "",
    // 审批进度与意见
    spjdyyj: "",
}

function initialData(resp) {
    console.log(resp);
    /**
     * 
     * 
     * KSBH: "KD093089"
KSMC: "江苏桐昆恒阳化纤有限公司"
KSSH: "91321322MA23QFEN3L"
SPCQH: "99"
SPCQMC: "桐昆集团总部"
SPYJ: "↵财务结算员-初审：  2022-08-12 14:12:05"
SQDH: "CRTZ10220800261"
SQWTSFTPURL: "DJFTP/ftp/ES_CRM客商权限调整单/CRTZ10220800261/授权委托书.jpg"
SQZT: "审批中"
YYZZFTPURL: "DJFTP/ftp/ES_CRM客商权限调整单/CRTZ10220800261/营业执照.jpg"
    */
    const { KSBH, KSMC, KSSH, SPCQH, SPCQMC, SQDH, SQWTSFTPURL, YYZZFTPURL, SPYJ } = resp.list[0].Rows[0];
    const yyzzUrl = 'https://khxtpt.zjtkgf.com/api/wechat/downFtpImage?fileName=' + YYZZFTPURL;
    let SQZT = resp.list[0].Rows[0].SQZT;
    // SQZT = "被驳回"
    const sqwtsUrl = 'https://khxtpt.zjtkgf.com/api/wechat/downFtpImage?fileName=' + SQWTSFTPURL
    data = {
        SQDH: SQDH,
        yyzzfjUrl: {
            isLocal: false,
            val: yyzzUrl,
            filePath: "",
        },
        sqwtsfjUrl: {
            isLocal: false,
            val: sqwtsUrl,
            filePath: "",
        },
        qymc: KSMC,
        shtyxydm: KSSH,
        zlshcq: SPCQH,
        // 审批进度与意见
        spjdyyj: SPYJ,
    }

    $("#qymc").val(KSMC);
    $("#shtyxydm").val(KSSH)
    $("#shcq").val(SPCQMC);
    $("#shyj").val(SPYJ)
    $("#yyzz-file").attr("src", yyzzUrl);
    $("#sqwts-file").attr("src", sqwtsUrl);
    if (SQZT == '审批中') {
        // 完成处理的、或者等待处理的不能进行操作
        $("#shyj").css({ "display": "none" })
        $("#submit-btn").css({ "display": "none" })
    }
    if (SQZT == "已完成") {
        $("#back-btn").text("删除授权");
        $("#back-btn").click(function(){
            deleteAuth();
        })
        $("#submit-btn").text("设为默认");
        $("#submit-btn").click(function(){
            setDefault()
        })
        $("#spjdyyj-title").css({ "display": "none" })
        $("#shyj").css({ "display": "none" })
        $("#shcq").unbind()
        $("#shcq").focus(function () {
            $("#shcq").blur()
        })
        $("#yyzzfj").unbind()
        $("#sqwts").unbind()
        $("#qymc").focus(function () {
            $("#qymc").blur()
        })
        $("#shtyxydm").focus(function () {
            $("#shtyxydm").blur()
        })

    }
    if (SQZT == '被驳回') {
        $("#shyj").css({ "display": "" })
    }

}



var yyzzLoadingIndex;
$(document).ready(() => {

    console.log("ready")

    loadSubmitRecord()



    $("#spjdyyj-title").css({ "display": "none" })
    $("#shyj").css({ "display": "none" })
    // init();


    var upload = layui.upload;

    $("#submit-btn").click(function () {
        console.log('click btn')
        submit();
    })
    $("#back-btn").click(function () {
        history.go(-1)
    })



    $("#shcq").click(function () {
        clickShow()
    })
    $("#shcq").focus(function () {
        $("#shcq").blur()
    })

    loadSHCQ();

    upload.render({
        elem: "#yyzzfj",
        url: "/api/wechat/UploadHouseholdMap",
        choose: function (opt) {
            console.log('choose img', arguments)
            const file = opt.pushFile()
            console.log(file)
            const ks = Object.keys(file);
            yyzzLoadingIndex = layer.load();
            parseYYZZ(file[ks[0]])
        },
        done: function (res, index, upload) {
            layer.close(yyzzLoadingIndex);

            console.log(res);
            try {
                // 图片在服务器文件系统中的绝对位置
                const imgPathInServerFileSystem = res.list.split(",")[0];
                data['yyzzfjUrl'] = {
                    ...data['yyzzfjUrl'],
                    filePath: imgPathInServerFileSystem
                }
                layer.msg(res.message)
            } catch (err) {
                layer.msg(err);
            }
        },
    })
    upload.render({
        elem: "#sqwts",
        url: "/api/wechat/UploadHouseholdMap",
        choose: function (opt) {

            const file = opt.pushFile()

            const ks = Object.keys(file);
            data['sqwtsfjUrl'] = {
                ...data['sqwtsfjUrl'],
                val: window.URL.createObjectURL(file[ks[0]]),
                isLocal: true,
            }
            $("#sqwts-file").attr("src", data['sqwtsfjUrl'].val)
            console.log('set val ', data['sqwtsfjUrl'].val)
        },
        done: function (res, index, upload) {
            layer.close(yyzzLoadingIndex);

            console.log(res);
            try {
                // 图片在服务器文件系统中的绝对位置
                const imgPathInServerFileSystem = res.list.split(",")[0];
                data['sqwtsfjUrl'] = {
                    ...data['sqwtsfjUrl'],
                    filePath: imgPathInServerFileSystem,
                }

                // $("#sqwts-file").attr("src","https://khxtpt.zjtkgf.com/api/wechat/downFtpImage?fileName=DJFTP/ftp/ES_CRM%E5%AE%A2%E5%95%86%E6%9D%83%E9%99%90%E8%B0%83%E6%95%B4%E5%8D%95/CRTZ10220800261/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.jpg")
                layer.msg(res.message)
            } catch (err) {
                layer.msg(err);
            }
        },
    })

})


/**
 * 设为默认
 * param : {CompanyNumber : string}
 */
function setDefault(){
    const params = {
        action : "SetDefaultCompany",
        CompanyNumber : getUrlParam("companyNumber"),
    }
    $.ajax({
        url  :REQUEST_URL ,
        type : "post",
        data:JSON.stringify(params),
        headers: REQUEST_HEADERS(),
        contentType : "application/json",
        success:function(r,t,x){
            layer.msg(r.message);
        }
    })
}

function deleteAuth(){
    const params = {
        action  :"CompanyDelete",
        CompanyNumber : getUrlParam("companyNumber"),
    }
    $.ajax({
        url  :REQUEST_URL ,
        type : "post",
        data:JSON.stringify(params),
        headers: REQUEST_HEADERS(),
        contentType : "application/json",
        success:function(r,t,x){
            layer.msg(r.message);
        }
    })
}